<?php
if (!defined('__COLA_DIR__')) exit;
/**
 * 多选框帮手
 *
 * @author edikud
 * @package Form
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

class Form_Checkbox extends Form_Group
{
    /**
     * 选择值
     *
     * @access private
     * @var array
     */
    private $_options = array();

    /**
     * 初始化当前输入项
     *
     * @access public
     * @param string $name 表单元素名称
     * @param array $options 选择项
     * @return Element
     */
    public function input($name = NULL, array $options = NULL)
    {
        foreach ($options as $value => $label) {
			self::$uniqueId ++;
            $this->_options[$value] = new Element('input');
            $item = $this->multiline();
			$id = 'input-' . self::$uniqueId;

            $item->set($this->_options[$value]
			    ->setAttr('name', $name . '[]')
                ->setAttr('type', 'checkbox')
                ->setAttr('value', $value)
			    ->setAttr('id', $id));

            $labelItem = new Element('label');
            $item->set($labelItem->setAttr('for', $id)->set($label));
            $this->set($item);
        }

        return current($this->_options);
    }

    /**
     * 设置表单元素值
     *
     * @access protected
     * @param mixed $value 表单元素值
     * @return void
     */
    protected function _value($value)
    {
        $values = is_array($value) ? $value : array($value);

        foreach ($this->_options as $option) {
            $option->removeAttr('checked');
        }

        foreach ($values as $value) {
            if (isset($this->_options[$value])) {
                $this->_options[$value]->setAttr('checked', 'true');
            }
        }
    }
}
